package to3;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.SimpleDateFormat;

public class ParkerenFrame extends javax.swing.JFrame {

    private Parkeerterrein p1;
    private KlantenLijst klantenLijst;
    private String filter;
    private String selectedKlantnr = "";
    private Klant selectedKlant;

    public ParkerenFrame() {

        initComponents();
        setVisible(true);

        ////////SCHERM IN MIDDEN////////
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = this.getSize();

        int windowX = Math.max(0, (screenSize.width - windowSize.width) / 2);
        int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);

        this.setLocation(windowX, windowY);
        ///////////////////////////////1

        this.setDefaultCloseOperation(this.DO_NOTHING_ON_CLOSE);
        filter = "";
        selectedKlantLabel.setText(selectedKlantnr);
        p1 = new Parkeerterrein();
        klantenLijst = new KlantenLijst();
        try {
            readFile();
        } catch (IOException ex) {
            Logger.getLogger(ParkerenFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        fillListBeschikbaar(filter);
        fillListBezet();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listBeschikbaar = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listBezet = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        btn_Reserveer = new javax.swing.JButton();
        btn_Vrijmaken = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        btn_DelFilter = new javax.swing.JButton();
        btn_Close = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        btn_Filter = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        selectedKlantLabel = new javax.swing.JLabel();
        btn_SelecteerKlant = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setFocusTraversalPolicyProvider(true);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Parkeren");

        jLabel2.setText("Beschikbare plaatsen:");

        jScrollPane1.setViewportView(listBeschikbaar);

        listBezet.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(listBezet);

        jLabel3.setText("Bezette plaatsen:");

        btn_Reserveer.setText("Reserveer plaats");
        btn_Reserveer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ReserveerActionPerformed(evt);
            }
        });

        btn_Vrijmaken.setText("Parkeerplaats vrij maken");
        btn_Vrijmaken.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_VrijmakenActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "auto", "bestelwagen", "vrachtwagen/bus" }));

        btn_DelFilter.setText("Verwijder filter");
        btn_DelFilter.setEnabled(false);
        btn_DelFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_DelFilterActionPerformed(evt);
            }
        });

        btn_Close.setText("Hoofdmenu");
        btn_Close.setPreferredSize(new java.awt.Dimension(164, 46));
        btn_Close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CloseActionPerformed(evt);
            }
        });

        jLabel4.setText(" Nr");

        jLabel5.setText("Nr");

        jLabel6.setText("Type");

        btn_Filter.setText("Filter");
        btn_Filter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_FilterActionPerformed(evt);
            }
        });

        jTextField1.setText("Klantnummer");

        jLabel7.setText("geselecteerde klant:");

        selectedKlantLabel.setText("geen");

        btn_SelecteerKlant.setText("selecteer klant");
        btn_SelecteerKlant.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_SelecteerKlantActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btn_Close, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(btn_Reserveer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addGap(26, 26, 26)
                                        .addComponent(jLabel6)))
                                .addGap(36, 36, 36)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btn_Filter)
                                    .addComponent(btn_DelFilter))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79, Short.MAX_VALUE)
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                                        .addComponent(btn_Vrijmaken)))
                                .addGap(47, 47, 47))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btn_SelecteerKlant)
                                .addGap(78, 78, 78)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(selectedKlantLabel)
                                .addContainerGap())))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(selectedKlantLabel)
                    .addComponent(btn_SelecteerKlant))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btn_Filter)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_DelFilter))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(jLabel6))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2)
                            .addComponent(jScrollPane1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btn_Reserveer)
                            .addComponent(btn_Vrijmaken, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 246, Short.MAX_VALUE)
                .addComponent(btn_Close, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void readFile() throws IOException {
        p1.clearParkeerplaats();
        FileReader fr = new FileReader("parkeerplaatsen.txt");
        BufferedReader br = new BufferedReader(fr);

        while (true) {
            String regel = br.readLine();
            if (regel == null) {
                break;
            }
            Scanner sc = new Scanner(regel);
            sc.useDelimiter("\\s*,\\s*");
            String type = sc.next();
            String plaats = sc.next();
            String status = sc.next();
            if (status.equals("beschikbaar")) {
                p1.addParkeerplaats(type, plaats, status);
            } else {
                String klantnr = sc.next();
                String beginDate = sc.next();
                p1.addParkeerplaats(type, plaats, status, klantnr, beginDate);
            }
            sc.close();
        }
// klaar met lezen uit file

        br.close();
        fr.close();

// Uitlezen van de arraylist:
    }
///////////

    private void btn_CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CloseActionPerformed
        try {
            writeParkeerplaatsen();
        } catch (IOException ex) {
            Logger.getLogger(ParkerenFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        hoofdMenu hM = new hoofdMenu();
        this.dispose();
    }//GEN-LAST:event_btn_CloseActionPerformed

    private void writeParkeerplaatsen() throws IOException {
        List<Parkeerplaats> listP = p1.getParkeerplaatsen();
        FileWriter fw = new FileWriter("parkeerplaatsen.txt");
        PrintWriter pw = new PrintWriter(fw);
        boolean eersteKeer = false;
        for (Parkeerplaats pp : listP) {
            if (eersteKeer == false) {
                if (pp.getStatus().equals("beschikbaar")) {
                    pw.print(pp.getType() + ", " + pp.getPlaats() + ", " + pp.getStatus());
                } else {
                    pw.print(pp.getType() + ", " + pp.getPlaats() + ", " + pp.getStatus() + ", " + pp.getKlantNr() + ", " + pp.getBeginDate());
                }
                eersteKeer = true;
            } else {
                if (pp.getStatus().equals("beschikbaar")) {
                    pw.print("\n" + pp.getType() + ", " + pp.getPlaats() + ", " + pp.getStatus());
                } else {
                    pw.print("\n" + pp.getType() + ", " + pp.getPlaats() + ", " + pp.getStatus() + ", " + pp.getKlantNr() + ", " + pp.getBeginDate());
                }
            }
        }
        pw.close();
        fw.close();
    }

    private void btn_DelFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_DelFilterActionPerformed
        filter = "";
        fillListBeschikbaar(filter);
        btn_DelFilter.setEnabled(false);
    }//GEN-LAST:event_btn_DelFilterActionPerformed

    private void btn_ReserveerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ReserveerActionPerformed
        //System.out.println(" HOI " + selectedKlantnr);
        if (selectedKlant != null) {
            List<Object> valueList = listBeschikbaar.getSelectedValuesList();
            List<Parkeerplaats> ppList = new ArrayList<>();
            for (Object o : valueList) {
                Parkeerplaats tempPp = p1.getParkeerPlaats(o.toString().substring(0, 3));
                ppList.add(tempPp);
            }
            for (Parkeerplaats pp : ppList) {
                pp.setStatus("bezet");
                pp.setKlantnr(selectedKlantnr);
                pp.setBegin(now());
            }
            fillListBeschikbaar(filter);
            fillListBezet();
        }else{
            JOptionPane.showMessageDialog(null, "Selecteer eerst een klant", "FOUT", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btn_ReserveerActionPerformed

    public static String now() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(cal.getTime());
    }

    private void btn_VrijmakenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_VrijmakenActionPerformed

        List<Object> valueList = listBezet.getSelectedValuesList();
        List<Dienst> ppList = new ArrayList<>();
        for (Object o : valueList) {
            Parkeerplaats tempPp = p1.getParkeerPlaats(o.toString().substring(0, 3));
            tempPp.berekenAantal(now());
            ppList.add(tempPp);
        }
        try {
            writeParkeerplaatsen();
        } catch (IOException ex) {
            Logger.getLogger(ParkerenFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        BetaalScherm bT = new BetaalScherm(selectedKlant);
        bT.addList(ppList);
        bT.setReturnScreen("parkeren");
        this.dispose();
        //GA EERST NAAR BETAALSCHERM EN STUUR PPLIST MEE
    }//GEN-LAST:event_btn_VrijmakenActionPerformed

    private void btn_FilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_FilterActionPerformed
        btn_DelFilter.setEnabled(true);
        fillListBeschikbaar(jComboBox1.getSelectedItem().toString());
    }//GEN-LAST:event_btn_FilterActionPerformed

    private void btn_SelecteerKlantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_SelecteerKlantActionPerformed
        if (klantenLijst.checkNr(jTextField1.getText())) {
            selectedKlantnr = jTextField1.getText();
            selectedKlantLabel.setText(selectedKlantnr);
            selectedKlant = klantenLijst.getKlant(selectedKlantnr);
        } else {
            JOptionPane.showMessageDialog(null, "Klant niet bekend!", "FOUT", JOptionPane.ERROR_MESSAGE);
        }
        fillListBezet();
    }//GEN-LAST:event_btn_SelecteerKlantActionPerformed

    public void setBeschikbaar(List<Dienst> ppList) {
        for (Dienst tempPp : ppList) {
            Parkeerplaats pp1 = (Parkeerplaats) tempPp;
            Parkeerplaats pp = p1.getParkeerPlaats(pp1.getPlaats());
            selectedKlantnr = pp.getKlantNr();
            selectedKlantLabel.setText(selectedKlantnr);
            pp.setStatus("beschikbaar");
            pp.setKlantnr("");
            pp.setBegin("");
        }
        fillListBeschikbaar(filter);
        fillListBezet();
    }

    private void fillListBeschikbaar() {
        List<Parkeerplaats> tempList = p1.getBeschikbareParkeerplaatsen();
        String s = "";
        for (Parkeerplaats pp : tempList) {
            s = s + pp.getPlaats() + "      " + pp.getType() + ",";
        }
        final String[] sarray = stringtoArray(s, ",");
        listBeschikbaar.setModel(new javax.swing.AbstractListModel() {

            String[] strings = sarray;

            public int getSize() {
                return strings.length;
            }

            public Object getElementAt(int i) {
                return strings[i];
            }
        });
    }

    private void fillListBeschikbaar(String filter) {
        if (filter == "") {
            fillListBeschikbaar();
        } else {
            List<Parkeerplaats> tempList = p1.getBeschikbareParkeerplaatsen();
            String s = "";
            this.filter = filter;
            for (Parkeerplaats pp : tempList) {
                if (pp.getType().equals(filter)) {
                    s = s + pp.getPlaats() + "      " + pp.getType() + ",";
                }
                final String[] sarray = stringtoArray(s, ",");
                listBeschikbaar.setModel(new javax.swing.AbstractListModel() {

                    String[] strings = sarray;

                    public int getSize() {
                        return strings.length;
                    }

                    public Object getElementAt(int i) {
                        return strings[i];
                    }
                });
            }
        }
    }

    private void fillListBezet() {
        List<Parkeerplaats> tempList = p1.getBezetteParkeerplaatsen();
        String s = "";
        for (Parkeerplaats pp : tempList) {
            if (pp.getKlantNr().equals(selectedKlantnr)) {
                s = s + pp.getPlaats() + ",";
            }
        }
        final String[] sarray = stringtoArray(s, ",");
        listBezet.setModel(new javax.swing.AbstractListModel() {

            String[] strings = sarray;

            public int getSize() {
                return strings.length;
            }

            public Object getElementAt(int i) {
                return strings[i];
            }
        });
    }

    private String[] stringtoArray(String s, String sep) {
        // convert a String s to an Array, the elements
        // are delimited by sep
        // NOTE : for old JDK only (<1.4).
        //        for JDK 1.4 +, use String.split() instead
        StringBuffer buf = new StringBuffer(s);
        int arraysize = 1;
        for (int i = 0; i < buf.length(); i++) {
            if (sep.indexOf(buf.charAt(i)) != -1) {
                arraysize++;
            }
        }
        String[] elements = new String[arraysize];
        int y, z = 0;
        if (buf.toString().indexOf(sep) != -1) {
            while (buf.length() > 0) {
                if (buf.toString().indexOf(sep) != -1) {
                    y = buf.toString().indexOf(sep);
                    if (y != buf.toString().lastIndexOf(sep)) {
                        elements[z] = buf.toString().substring(0, y);
                        z++;
                        buf.delete(0, y + 1);
                    } else if (buf.toString().lastIndexOf(sep) == y) {
                        elements[z] = buf.toString().substring(0, buf.toString().indexOf(sep));
                        z++;
                        buf.delete(0, buf.toString().indexOf(sep) + 1);
                        elements[z] = buf.toString();
                        z++;
                        buf.delete(0, buf.length());
                    }
                }
            }
        } else {
            elements[0] = buf.toString();
        }
        buf = null;
        return elements;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Close;
    private javax.swing.JButton btn_DelFilter;
    private javax.swing.JButton btn_Filter;
    private javax.swing.JButton btn_Reserveer;
    private javax.swing.JButton btn_SelecteerKlant;
    private javax.swing.JButton btn_Vrijmaken;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JList listBeschikbaar;
    private javax.swing.JList listBezet;
    private javax.swing.JLabel selectedKlantLabel;
    // End of variables declaration//GEN-END:variables
}
